package indi.h.proxy;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ClassProxy<T> implements MethodInterceptor {
	private T target;
	private Map<Method, ProxyFilter<T>> proxyFilter;

	public ClassProxy(T target, Map<Method, ProxyFilter<T>> proxyFilter) {
		super();
		this.target = target;
		this.proxyFilter = proxyFilter;
	}

	public T getTarget() {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(target.getClass());
		enhancer.setCallback(this);
		enhancer.setClassLoader(target.getClass().getClassLoader());
		return (T) enhancer.create();
	}

	@Override
	public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
		// TODO Auto-generated method stub
		if (proxyFilter.get(arg1) != null) {
			ProxyFilter<T> filter = proxyFilter.get(arg1);
			filter.before();
			Object invoke = arg1.invoke(this.target, arg2);
			filter.after();
			return invoke;
		}
		return arg1.invoke(this.target, arg2);
	}

	public static void main(String[] args) throws Exception {
		Method method = TestImp.class.getMethod("sb");
		TestImp pt = new TestImp();
		
		ProxyFilter proxyFilter2 = new ProxyFilter() {

			@Override
			public void before() {
				// TODO Auto-generated method stub
				System.out.println("before");
			}

			@Override
			public void after() {
				// TODO Auto-generated method stub
				System.out.println("after");
			}

			@Override
			public void init(Object t) {
				// TODO Auto-generated method stub

			}
		};

		Map map=new HashMap<>();
		map.put(method, proxyFilter2);
		
	//	ClassProxy cp1 = new ClassProxy<>(pt,map);

		//TestImp target3 = (TestImp) cp1.getTarget();
	//	target3.sb();
		
		InterFaceProxy<ProxyTestInter> ifp=new InterFaceProxy<ProxyTestInter>(pt, map);
		ProxyTestInter target4 = ifp.getTarget();
		target4.sb();

	}

}
